/**
 * Created by Freeman on 2017/3/16.
 */
import userApi from '../../api/user'
import utils from '../../commons/utils'
import * as types from '../types'
import * as constants from '../../AppConstants'

export const login = (context, payload) => {
  return userApi.login(payload)
    .then(resp => {
      if (resp.status === 200) {
        utils.storageUserInfo(resp.data, payload.username)
      }
      return resp.data
    })
    .catch(err => {
      return Promise.reject(err)
    })
}
export const register = (context, payload) => {
  return userApi.register(payload)
    .then(resp => {
      console.log(resp)
      if (resp.status === 200) {
        utils.storageUserInfo(resp.data, payload.username)
        return resp.data
      } else {
        //TODO
      }

    })
    .catch(err => {
      return Promise.reject(err)
    })
}

/**
 * 发送短信验码
 * @param commit
 * @param payload 手机号和验证码类型
 */
export const sendSmsVerifyCode = function ({commit}, payload) {
  return userApi.sendSmsVerifyCode(payload.username, payload.type)
    .then(resp => {
        if (resp.status === 200) {
          commit(types.UPDATE_TIP, '验证码发送成功')
          let countDown = constants.SMS_VERIFY_CODE_COUNT_DOWN
          let t = window.setInterval(() => {
            if (countDown === 0) {
              window.clearInterval(t)
            }
            commit(types.UPDATE_VERIFYCODE_COUNT_DOWN, countDown--)
          }, 1000)
        }
      }
    )
    .catch(err => {
      return Promise.reject(err)
    })
}
